package router

import (
	goods "api-gateway/basic/goods_proto"
	"api-gateway/basic/inits"
	order "api-gateway/basic/order_proto"
	"api-gateway/handler/api"
	"api-gateway/handler/request"
	"github.com/gin-gonic/gin"
	"google.golang.org/api/logging/v2"
	"log"
)

func AlipayRouter(v1 *gin.RouterGroup) {
	Alipay := v1.Group("alipay")
	{
		Alipay.POST("/callback", api.Callback) // 支付宝回调
		Alipay.POST("/alipay", api.Alipay)     //支付宝支付
	}
}

// 回调
func Callback(c *gin.Context) {
	var req request.Callback
	if err := c.ShouldBind(&req); err != nil {
		c.String(400, "failure")
		return
	}

	// 避免未使用导入导致编译错误（不影响业务逻辑）
	//_ = pkg.AliPay{}
	_ = logging.LogEntry{}

	// 校验订单是否存在
	val, err := inits.OrderClient.DetailOrder(c, &order.DetailOrderReq{
		OrderNo: req.OutTradeNo,
	})
	if err != nil || val == nil {
		log.Println("订单信息不存在")
		return
	}

	// 校验支付状态
	if req.TradeStatus == "TRADE_SUCCESS" {
		_, err = inits.OrderClient.UpdateOrder(c, &order.UpdateOrderReq{
			Id:          val.Id,
			OrderStatus: 1,
		})
		if err != nil {
			return
		}
		log.Println("支付成功")
		return
	} else {

		_, err = inits.GoodsClient.UpdateShopCarNum(c, &goods.UpdateShopCarNumReq{
			GoodsId: int64(val.GoodsId),
			Num:     int64(val.GoodsNum),
		})
		if err != nil {
			log.Println("修改库存失败")
			return
		}
		_, err = inits.OrderClient.UpdateOrder(c, &order.UpdateOrderReq{
			Id:          val.Id,
			OrderStatus: 2,
		})
		if err != nil {
			return
		}
		log.Println("支付失败")
	}
	// 支付宝回调必须返回 success
	log.Println("支付宝回调成功")
}
